import React from 'react';
import { Row, Col, Icon } from 'antd';
import JunctionType from '../../../../../components/Conditions/JunctionType';
import { randomKey } from '../../../../../utils/utils';
import WarnConditionGroupItem from './item';
import { cloneDeep } from 'lodash';

const WarnConditionGroup = (props) => {
  const { isFirst, value, onChange, onGroupDel, isDelBtn } = props;

  const tempValue = cloneDeep(value);

  const handleChangeJunctionType = (junction_type) => {
    tempValue.junction_type = junction_type;
    onChange && onChange(tempValue);
  };

  // 增加条件
  const onAdd = () => {
    tempValue.conditions.push({
      id: randomKey(),
      junction_type: 'and',
      left_var_code: '',
      left_var_name: '',
      left_var_type: 'feature', // 左变量类型 默认 feature
      right_var_type: 'literal', // 右变量类型 默认 literal
    });
    onChange && onChange(tempValue);
  };

  // 删除条件
  const onDel = (index) => {
    tempValue.conditions.splice(index, 1);
    if (!index) {
      tempValue.conditions[0].junction_type = 'none';
    }
    onChange && onChange(tempValue);
  };

  const handleItemChange = (value, id) => {
    tempValue.conditions.forEach((item, index) => {
      if (item.id === id) {
        tempValue.conditions[index] = value;
      }
    });
    onChange && onChange(tempValue);
  };

  const { junction_type, conditions } = value;
  return (
    <div>
      {isFirst && (
        <Row>
          <Col span={4}>
            <JunctionType value={junction_type} onChange={handleChangeJunctionType} />
          </Col>
        </Row>
      )}
      <div className='warn-condition-group'>
        {conditions.map((item, index) => (
          <WarnConditionGroupItem
            {...props}
            value={item}
            key={item.id}
            isAddBtn={index === conditions.length - 1}
            isDelBtn={conditions.length !== 1}
            onAdd={onAdd}
            onDel={() => onDel(index)}
            onChange={(value) => handleItemChange(value, item.id)}
          />
        ))}
        {isDelBtn && <Icon type='minus-circle' className='close' onClick={() => onGroupDel && onGroupDel()} />}
      </div>
    </div>
  );
};

export default WarnConditionGroup;
